//
//  ProductImgTextIntroductViewController.m
//  LazyCat
//
//  Created by Abner on 16/5/3.
//  Copyright © 2016年 zhanshu. All rights reserved.
//

#import "ProductImgTextIntroductViewController.h"
#import "AJPhotoPickerViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import "AJPhotoBrowserViewController.h"

//imgText
#import "UIImage+SLImage.h"
#import "PlaceholderTextView.h"
#import "ImageTextAttachment.h"
#import "NSAttributedString+RichText.h"
#import "UIView+TYAlertView.h"

#import "CropImgViewController.h"
#import "NSData+Base64.h" //图片转base64

#define ImageTag 800
#define MaxLength (2000)
#define BARandomData arc4random_uniform(100)
#define bottomViewH 50

@interface ProductImgTextIntroductViewController ()<AJPhotoPickerProtocol,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextViewDelegate>
{
    UIButton *cancleBtn;
    float image_h;
    NSString *_imageBizno;
    NSString *bizNosStr;
    
    
}
//@property(nonatomic,strong)AJPhotoPickerViewController *picker; //选择照片
@property (strong, nonatomic) NSMutableArray *photos;
@property (strong, nonatomic) NSMutableArray *finalDatas;

@property (nonatomic, copy)NSString *imageName;//图片名
@property (nonatomic, strong)NSData   *imageData;//图片流
@property (nonatomic, strong) PlaceholderTextView *messageInputView;
@property (nonatomic,assign) NSUInteger location;  //纪录变化的起始位置
@property (nonatomic,strong) NSMutableAttributedString * locationStr;

@property (nonatomic,assign) CGFloat lineSapce;    //行间距
@property(nonatomic,strong)UIView * bottomView;//底部界面


@end

@implementation ProductImgTextIntroductViewController

-(NSMutableArray *)photos
{
    if (_photos == nil) {
        _photos = [NSMutableArray array];
    }
    return _photos;
}

-(NSMutableArray *)finalDatas
{
    if (_finalDatas == nil) {
        _finalDatas = [NSMutableArray array];
    }
    return _finalDatas;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.extendedLayoutIncludesOpaqueBars = NO;
    self.modalPresentationCapturesStatusBarAppearance = NO;
    image_h = 0;
    bizNosStr = @"";
    
    self.location=0;
    self.lineSapce=5;
    [self createView];
    [self creatNav];
    [self creatBottomView];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardshow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardhide:) name:UIKeyboardWillHideNotification object:nil];
    
}
-(void)creatBottomView
{
   
    self.bottomView  = [[UIView alloc]init];
    self.bottomView.backgroundColor = SetColorRGBValue(0xf0f0f0, 1.0);
    self.bottomView.frame = CGRectMake(0, ScreenHeight, ScreenWidth, bottomViewH);
    [self.view addSubview:self.bottomView];
    
    //uiviewline 线
    UIView * lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 0.5)];
    lineView.backgroundColor = [UIColor lightGrayColor];
    lineView.alpha = 0.3;
    [self.bottomView addSubview:lineView];
    
    UIButton *jiaCuBt = [UIButton buttonWithType:UIButtonTypeCustom];
    [jiaCuBt setImage:[UIImage imageNamed:@"icon_jiacu.png"] forState:UIControlStateNormal];
    jiaCuBt.frame = CGRectMake(20, 13, 24, 24);
    [jiaCuBt addTarget:self action:@selector(jiaCuBtClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView addSubview:jiaCuBt];
    
    UIButton *changeImgBt = [UIButton buttonWithType:UIButtonTypeCustom];
    [changeImgBt setImage:[UIImage imageNamed:@"icon_photo.png"] forState:UIControlStateNormal];
    changeImgBt.frame = CGRectMake(CGRectGetMaxX(jiaCuBt.frame)+15, 13, 24, 24);
    [changeImgBt addTarget:self action:@selector(changeImgBtClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView addSubview:changeImgBt];

}
- (void)createView {
    
    self.messageInputView = [[PlaceholderTextView alloc] initWithFrame:CGRectMake(10, 64, ScreenWidth-20, ScreenHeight-64)];
    self.messageInputView.placeholder = @"请输入商品文字介绍";
    self.messageInputView.placeholderColor = KPlaceholderColor;
    self.messageInputView.textColor = KAddLeftLbColor;
    self.messageInputView.delegate = self;
    self.messageInputView.showsVerticalScrollIndicator = NO;
    self.messageInputView.font = FontSet(16);
    self.messageInputView.editable = YES;
    [self.messageInputView becomeFirstResponder];
    [self.view addSubview:self.messageInputView];
    
    self.messageInputView.backgroundColor = SetColorRGBValue(0xF9F9F9, 1.0);;
    
    NSRange wholeRange = NSMakeRange(0, self.messageInputView.textStorage.length);
    [self.messageInputView.textStorage removeAttribute:NSFontAttributeName range:wholeRange];
    [self.messageInputView.textStorage removeAttribute:NSForegroundColorAttributeName range:wholeRange];
    //字体颜色
    [self.messageInputView.textStorage addAttribute:NSForegroundColorAttributeName value:KAddLeftLbColor range:wholeRange];
    
    //字体
    [self.messageInputView.textStorage addAttribute:NSFontAttributeName value:FontSet(16) range:wholeRange];
}

#pragma mark --- "加粗"按钮点击事件
-(void)jiaCuBtClicked
{
    NSLog(@"加粗点击");
    
}

#pragma mark --- "选图"按钮点击事件
-(void)changeImgBtClicked
{
    NSLog(@"选图点击");
    //只能选择一张图片
    AJPhotoPickerViewController *picker =[[AJPhotoPickerViewController alloc] init];
    picker.delegate = self;
    picker.assetsFilter = [ALAssetsFilter allPhotos];
    picker.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
        return YES;
    }];
    picker.showEmptyGroups = YES;
    //跳转到相册
    [self presentViewController:picker animated:YES completion:^{
        
    }];
}


#pragma mark 当键盘出现或改变时调用
-(void)keyBoardshow:(NSNotification *)notification{
    NSDictionary *info=[notification userInfo];
    NSValue *avalue=[info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect=[self.view convertRect:[avalue CGRectValue] fromView:nil];
    double keyboardHeight=keyboardRect.size.height;//键盘的高度
    [UIView animateWithDuration:0.2 animations:^{
        self.bottomView.frame=CGRectMake(0, ScreenHeight-keyboardHeight-bottomViewH, ScreenWidth, bottomViewH);
        self.messageInputView.frame = CGRectMake(10, 64, ScreenWidth-20, ScreenHeight-keyboardHeight-bottomViewH-64);
    }];
   
}
-(void)keyBoardhide:(NSNotification *)notification{
    [UIView animateWithDuration:0.2 animations:^{
        self.bottomView.frame=CGRectMake(0, ScreenHeight, ScreenWidth, bottomViewH);
        self.view.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
        self.messageInputView.frame = CGRectMake(10, 64, ScreenWidth-20, ScreenHeight-64);
    }];
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

#pragma mark --- 设置界面UI
-(void)creatNav
{
    [self initNav:@"商品图文描述" doBack:YES];
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 63, ScreenWidth, 1)];
    lineView.backgroundColor = [UIColor lightGrayColor];
    lineView.alpha = 0.2;
    [self.navBar addSubview:lineView];
    
    self.view.frame = CGRectMake(0, 64, ScreenWidth, ScreenHeight-64);
    self.view.backgroundColor = SetColorRGBValue(0xF9F9F9, 1.0);
    
    //右边的"完成"按钮
    UIButton *completeBt = [UIButton buttonWithType:UIButtonTypeCustom];
    [completeBt setTitle:@"完成" forState:UIControlStateNormal];
    completeBt.frame = CGRectMake(ScreenWidth-8-40, 20, 40, 44);
    [completeBt setHitTestEdgeInsets:UIEdgeInsetsMake(0, -10, 0, -10)];
    [completeBt setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    completeBt.titleLabel.font = FontSet(15);
    [self.navBar addSubview:completeBt];
    [completeBt addTarget:self action:@selector(completeBtClicked) forControlEvents:UIControlEventTouchUpInside];
    
}

#pragma mark --- "完成"点击事件
-(void)completeBtClicked
{
    NSLog(@"完成点击事件");
    [self.view endEditing:YES];
    
    NSArray * arr=[self.messageInputView.attributedText getArrayWithAttributed];
    NSLog(@"发布文章title---%@",arr);

    if (arr.count>0) {

        NSString *textStr = @"";
        NSString *identifier = @"LCLCLCIMGIMGIMG8";
        for (NSDictionary * dict in arr) {
            
            NSLog(@"发布文章title---%@",[dict objectForKey:@"title"]);
            NSString *str =[dict objectForKey:@"title"];

            textStr = [textStr stringByAppendingString:str];
            
            if ([textStr containsString:identifier]) {
                //拼接的文字
                NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                NSString *lcstr = [textStr substringToIndex:textStr.length-identifier.length-2];

                //取出图片
                NSString *photoNum = [textStr substringFromIndex:textStr.length-identifier.length-2];
                NSLog(@"pppp9999999pppp-------%@\n--%@",lcstr,photoNum);

                NSString *photoNum1 = [photoNum substringFromIndex:15];
                NSInteger photoNumCount = [photoNum1 integerValue]-800;
                NSData *imgData = UIImageJPEGRepresentation(self.photos[photoNumCount], 0.8);
                NSString *imgbase64Str = [imgData base64Encoding];
                NSString *str64 = [self encodeURL:imgbase64Str];
                
                [dict setValue:str64 forKey:@"img"];
                [dict setValue:@"jpg" forKey:@"ext"];
                [dict setValue:lcstr forKey:@"text"];
                [self.finalDatas addObject:dict];
                textStr = @"";

            }
            
        }
        //执行完for循环后，如果还有，就再加入
        if (textStr.length > 0) {
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
         
            [dict setValue:@"" forKey:@"img"];
            [dict setValue:@"jpg" forKey:@"ext"];
            [dict setValue:textStr forKey:@"text"];
            [self.finalDatas addObject:dict];
        }

    }
    
    if (self.overImgTextIntroBlock) {
        self.overImgTextIntroBlock(@"1");
    }
    
    //NSLog(@"%s---\n---%@-----%@",__func__,self.photos,self.finalDatas);

    [self.navigationController popViewControllerAnimated:YES];
}
-(void)viewDidDisappear:(BOOL)animated
{
    if (self.overImgTextIntroBlock) {
        self.overImgTextIntroBlock(@"1");
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - BoPhotoPickerProtocol
- (void)photoPickerDidCancel:(AJPhotoPickerViewController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)photoPicker:(AJPhotoPickerViewController *)picker didSelectAssets:(NSArray *)assets {
    
    //[self.photos addObjectsFromArray:assets];
    if (assets.count == 1) {
        ALAsset *asset = assets[0];
        UIImage *tempImg = [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
        //选择照片后就存入照片数组
        [self.photos addObject:tempImg];
        
        CropImgViewController *cropVC = [[CropImgViewController alloc]init];
        cropVC.scropedImg = (UIImage *)[self.photos lastObject];
        __weak typeof(self) weakSelf = self;
        cropVC.overCropedImgBlock = ^(UIImage *cropedImg){
            
            [weakSelf.photos replaceObjectAtIndex:weakSelf.photos.count-1 withObject:cropedImg];
            //[weakSelf.tableView reloadData];
            
            ImageTextAttachment *imageTextAttachment = [ImageTextAttachment new];
            UIImage *image = (UIImage *)[weakSelf.photos lastObject];
          
            //Set tag and image
            imageTextAttachment.image =image;
            //Set image size
            imageTextAttachment.imageSize = CGSizeMake(ScreenWidth - 20,(ScreenWidth-20)*3/4);
            
            //Insert image image
            [weakSelf.messageInputView.textStorage insertAttributedString:[NSAttributedString attributedStringWithAttachment:imageTextAttachment] atIndex:weakSelf.messageInputView.selectedRange.location];
            
            //Move selection location
            weakSelf.messageInputView.selectedRange = NSMakeRange(weakSelf.messageInputView.selectedRange.location + 1, weakSelf.messageInputView.selectedRange.length);
            
            //设置字的设置
            [weakSelf setInitLocation];
            
            NSInteger photoNum = weakSelf.photos.count - 1;
            NSInteger lcnum = (NSInteger)ImageTag+photoNum;
            imageTextAttachment.imageTag = [NSString stringWithFormat:@"LCLCLCIMGIMGIMG%ld",(long)lcnum];
            
            //适配屏幕宽度
            [picker dismissViewControllerAnimated:YES completion:nil];
            [self.messageInputView becomeFirstResponder];
            
        };
        [self.navigationController pushViewController:cropVC animated:YES];
        NSLog(@" //选择照片后就存入照片数组---%@",self.photos);
    }

    NSLog(@"%s---\n---%@",__func__,self.photos);
    
    [picker dismissViewControllerAnimated:NO completion:nil];
    
}

- (void)photoPicker:(AJPhotoPickerViewController *)picker didSelectAsset:(ALAsset *)asset {
    NSLog(@"%s",__func__);
}

- (void)photoPicker:(AJPhotoPickerViewController *)picker didDeselectAsset:(ALAsset *)asset {
    NSLog(@"%s",__func__);
}

//超过最大选择项时
- (void)photoPickerDidMaximum:(AJPhotoPickerViewController *)picker {
    NSLog(@"%s",__func__);
}

//低于最低选择项时
- (void)photoPickerDidMinimum:(AJPhotoPickerViewController *)picker {
    NSLog(@"%s",__func__);
}

- (void)photoPickerTapCameraAction:(AJPhotoPickerViewController *)picker {
    [self checkCameraAvailability:^(BOOL auth) {
        if (!auth) {
            NSLog(@"没有访问相机权限");
            return;
        }
        
        [picker dismissViewControllerAnimated:NO completion:nil];
        UIImagePickerController *cameraUI = [UIImagePickerController new];
        cameraUI.allowsEditing = NO;
        cameraUI.delegate = self;
        cameraUI.sourceType = UIImagePickerControllerSourceTypeCamera;
        cameraUI.cameraFlashMode=UIImagePickerControllerCameraFlashModeAuto;
        
        [self presentViewController: cameraUI animated: YES completion:nil];
    }];
}

- (void)checkCameraAvailability:(void (^)(BOOL auth))block {
    BOOL status = NO;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if(authStatus == AVAuthorizationStatusAuthorized) {
        status = YES;
    } else if (authStatus == AVAuthorizationStatusDenied) {
        status = NO;
    } else if (authStatus == AVAuthorizationStatusRestricted) {
        status = NO;
    } else if (authStatus == AVAuthorizationStatusNotDetermined) {
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if(granted){
                if (block) {
                    block(granted);
                }
            } else {
                if (block) {
                    block(granted);
                }
            }
        }];
        return;
    }
    if (block) {
        block(status);
    }
}

#pragma mark - UIImagePickerDelegate
- (void)imagePickerControllerDidCancel:(UIImagePickerController *) picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)image:(UIImage*)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo {
    if (!error) {
        NSLog(@"保存到相册成功");
    }else{
        NSLog(@"保存到相册出错%@", error);
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
    UIImage *originalImage;
    if (CFStringCompare((CFStringRef) mediaType,kUTTypeImage, 0)== kCFCompareEqualTo) {
        originalImage = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage];
    }
    //self.imageView.image = originalImage;
    NSLog(@"8888%s---\n---%@",__func__,self.photos);

    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark --- UINavigationControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
}

#pragma mark --- 图片base64编码
 - (NSString*)encodeURL:(NSString *)string
 {
         NSString *newString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault, (CFStringRef)string, NULL, CFSTR(":/?#[]@!$ &'()*+,;=\"<>%{}|\\^~`"),kCFStringEncodingUTF8));
         if (newString) {
                 return newString;
             }
         return @"";
     }

-(void)setInitLocation
{    
    self.locationStr=nil;
    self.locationStr=[[NSMutableAttributedString alloc]initWithAttributedString:self.messageInputView.attributedText];
    self.messageInputView.font = [UIFont systemFontOfSize:20];
    self.messageInputView.textColor = [UIColor redColor];
    //重新设置位置
    self.location=self.messageInputView.textStorage.length;
    
}
@end
